package com.dtborad.myblog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dtborad.myblog.common.CommonErrorCode;
import com.dtborad.myblog.common.Result;
import com.dtborad.myblog.entity.Comments;
import com.dtborad.myblog.entity.Tags;
import com.dtborad.myblog.service.CommentService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/comment")
@Slf4j
@Api(tags = "评论模块")
public class CommentController {

    @Autowired
    private CommentService commentService;

    //分页
    @GetMapping("/list")
    public Result<Map<String, Object>> list(@RequestParam(defaultValue = "1") int pagenum,
                                            @RequestParam(defaultValue = "5") int pagesize,
                                            @RequestParam(defaultValue = "") Integer postid,
                                            @RequestParam(defaultValue = "") String commentcontent) {
        Page<Comments> currentPage = commentService.getAllCommentsByPageSize(pagenum, pagesize, postid, commentcontent);
        Map<String, Object> response = new HashMap<>();
        response.put("records", currentPage.getRecords());
        response.put("total", currentPage.getTotal());
        return Result.ofSuccess(response);
    }

    //删除评论
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable("id") int id) {
        try {
            LambdaQueryWrapper<Comments> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Comments::getCommentid, id);
            commentService.remove(queryWrapper);
            return Result.ofSuccess();
        } catch (Exception e) {
            return Result.ofFail(CommonErrorCode.FAILURE);
        }
    }

    //添加评论
    @PostMapping("/add")
    public Result<String> add(@RequestBody Comments comments) {
        try {
            commentService.save(comments);
            return Result.ofSuccess();
        } catch (Exception e) {
            return Result.ofFail(CommonErrorCode.FAILURE);
        }
    }
}
